package com.qf.data.service.impl;

import com.qf.common.constant.CacheConstant;
import com.qf.data.service.HeartBeatService;
import com.qf.data.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author 千锋健哥
 */
@Service
public class HeartBeatServiceImpl implements HeartBeatService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void savePing(String productKey, String deviceKey) {
        if (StringUtils.isEmpty(productKey) || StringUtils.isEmpty(deviceKey)) {
            return;
        }

        //redis中的key, device_ping_
        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING
                + "_" + productKey
                + "_" + deviceKey;

        //心跳数据保存到redis中
        redisUtil.setKey(key, "1", 30, TimeUnit.SECONDS);
    }

    @Override
    public Boolean findDeviceState(String productKey, String deviceKey) {
        if (StringUtils.isEmpty(productKey) || StringUtils.isEmpty(deviceKey)) {
            return false;
        }

        //redis中的key, device_ping_
        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING
                + "_" + productKey
                + "_" + deviceKey;

        //从redis中获取心跳数据
        String value = redisUtil.getKey(key, String.class);

        if ("1".equals(value)) {
            return true;
        } else {
            return false;
        }
    }

}
